package stl

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"runtime"
	"sync"

	x "gitee.com/shexk/plugin"
)

type DBCmd struct {
	err error
	DB  *Sqlite3
}

var (
	instance_dbcmd *DBCmd
	once_dbcmd     sync.Once
)

func GetDBCmd() *DBCmd {
	once_dbcmd.Do(func() {
		instance_dbcmd = NewDBCmd()
	})
	return instance_dbcmd
}
func (d *DBCmd) GetDB() *sql.DB {
	if d.DB != nil {
		if d.DB.DB != nil {
			return d.DB.DB
		}
	}
	return nil
}
func NewDBCmd() *DBCmd {
	return &DBCmd{DB: NewSqlite3()}
}
func GetResourcesDir(appMode bool) (string, error) {
	if runtime.GOOS != "darwin" {
		return "", nil
	}

	// 获取当前可执行文件路径
	execPath, err := os.Executable()
	if err != nil {
		return "", err
	}

	// 应用打包后，资源目录通常在：App.app/Contents/Resources/
	// 从可执行文件路径逆向推导（可执行文件在 App.app/Contents/MacOS/ 下）
	var resourcesDir string
	if appMode {
		resourcesDir = filepath.Join(filepath.Dir(execPath), "..", "Resources")
	} else {
		resourcesDir = filepath.Join(filepath.Dir(execPath), ".", "")
	}

	// 转换为绝对路径
	return filepath.Abs(resourcesDir)
}
func (d *DBCmd) OpenDB(DBName string) (bool, error) {
	appSupportDir, err := GetResourcesDir(RunMode)
	if err != nil {
		return false, err
	}
	dbPath := filepath.Join(appSupportDir, DBName)
	result, err := d.DB.OpenSqlite3(dbPath)
	d.err = err
	return result, err
}

func (d *DBCmd) ReadKeyValue(name string) string {
	if d.err != nil {
		fmt.Println("Open DB Error:" + d.err.Error())
		return ""
	}
	rows, err := d.DB.QuerySQL("Select value from KeyValue where Key='" + name + "'")
	if err != nil {
		fmt.Println("Read Record Error:" + err.Error())
		return ""
	}
	defer rows.Close()
	if rows.Next() {
		aes := ""
		if err = rows.Scan(&aes); err != nil {
			fmt.Println("Read Record Value Error:" + err.Error())
			return ""
		}
		return aes
	}
	return ""
}

type DBRequest struct {
	Name  string
	Value string
}

func (d *DBCmd) ProcessPluginMsg(msg *x.PluginMsg) {
	var data DBRequest
	if err := json.Unmarshal([]byte(msg.Option), &data); err != nil {
		return
	}
	switch data.Name {
	case "ReadKeyValue":
		value := d.ReadKeyValue(data.Value)
		msg.Data = []byte(value)
		//GetApp().SendToPlugin(msg.Sender.Name, msg)
	}
}
